package com.xiaotao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaotao.dto.GoodDto;
import com.xiaotao.entity.Good;
import com.xiaotao.entity.Order;
import com.xiaotao.entity.OrderItem;
import com.xiaotao.mapper.GoodMapper;
import com.xiaotao.mapper.OrderItemMapper;
import com.xiaotao.mapper.OrderMapper;
import com.xiaotao.publisher.CreateOrderPublisher;
import com.xiaotao.publisher.OrderDelayPublisher;
import com.xiaotao.service.OrderService;
import com.xiaotao.util.ConstantUtil;
import com.xiaotao.util.Result;
import com.xiaotao.util.SnowflakeIdGenerator;
import com.xiaotao.util.UserContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private GoodMapper goodMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private RedisTemplate redisTemplateInit;
    @Resource
    private OrderDelayPublisher orderDelayPublisher;
    @Resource
    private CreateOrderPublisher createOrderPublisher;

    @Override
    public Result addOrder(GoodDto goodDto) throws Exception {
        //判断库存是否充足
        List<Good> goodList = goodMapper.findGoodByIds(goodDto.getIds());
        List<String> collect = goodList.stream().filter(item -> item.getBuyNum() > item.getStoreCount())
                .map(Good::getName)
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            //库存不足
            return Result.get(500, "库存不足");
        }
        //库存充足创建订单
        Order order = new Order();
        SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator();
        String orderNum = String.valueOf(snowflakeIdGenerator.nextId());
        order.setOrderNum(orderNum);
        order.setUserId(UserContext.contextUserId());
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (int i = 0; i < goodList.size(); i++) {
            Good good = goodList.get(i);
            BigDecimal sum = good.getPrice().multiply(new BigDecimal(good.getBuyNum())).multiply(new BigDecimal(good.getDiscount()*0.1));
            totalPrice = totalPrice.add(sum);
        }
        order.setTotalPrice(totalPrice);
        order.setCreatetime(new Date());
        order.setAddressId(goodDto.getAddressId());
        order.setStatus(1);
        String jsonString = JSON.toJSONString(order);
        //redis缓存数据，保证幂等性
        redisTemplateInit.opsForValue().set(ConstantUtil.REDIS_CREATE_ORDER+orderNum,orderNum);
        //异步生成订单
        createOrderPublisher.send(jsonString);
        //15分钟未支付取消订单
        orderDelayPublisher.send(orderNum, 15000);
        //添加订单详情表
        List<OrderItem> orderItemList = new ArrayList<>();
        for (Good good : goodList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setGoodId(good.getId());
            orderItem.setGoodName(good.getName());
            orderItem.setPrice(good.getPrice());
            orderItem.setBuyNum(good.getBuyNum());
            orderItem.setSumPrice(good.getPrice().multiply(new BigDecimal(good.getBuyNum())).multiply(new BigDecimal(good.getDiscount()*0.1)));
            orderItem.setOrderNum(orderNum);
            orderItem.setCreateTime(new Date());
            orderItemList.add(orderItem);
        }
        orderItemMapper.batchAddOrderItem(orderItemList);
        //扣减库存
        updateCount(goodList);
        return Result.get(200, "操作成功", orderNum);
    }

    @Override
    public Result findById(String orderNum) {
        Order byOrderNum = orderMapper.findByOrderNum(orderNum);
        return byOrderNum!=null? Result.get(200,"查询成功",byOrderNum):
                Result.get(500,"查询失败");
    }

    @Override
    public Result findAll() {
        List<Order> list = orderMapper.findAll();
        return list!=null? Result.get(200,"查询成功",list):
                Result.get(500,"查询失败");
    }
    @Override
    public Result update(String orderNum) {
        Order orderNum1 = orderMapper.findByOrderNum(orderNum);
        if (orderNum1==null){
            return Result.get(500,"未查到订单");
        }
        Integer status = orderNum1.getStatus();
        if (status!=1){
            return Result.get(500,"已取消");
        }
        orderNum1.setStatus(2);
        orderMapper.updateStatus(orderNum1);
        return Result.get(200,"支付成功");
    }
    private void updateCount(List<Good> goodList) throws InterruptedException {
        for (int i = 0; i < goodList.size(); i++) {
            Good good = goodList.get(i);
            good.setStoreCount(good.getStoreCount() - good.getBuyNum());
            //将购买数量归1
            good.setBuyNum(1);
        }
        goodMapper.batchUpdateBook(goodList);
    }
}